"""
行为分析服务
实现异常行为检测、人群聚集检测、轨迹分析等功能
"""
import asyncio
import logging
import cv2
import numpy as np
from datetime import datetime, timedelta
from typing import List, Dict, Optional, Tuple, Any
from uuid import uuid4
import time
from collections import defaultdict, deque
from dataclasses import dataclass
from enum import Enum

from schemas.ai_algorithm import (
    BehaviorAnalysisResult, BehaviorType, DetectionResult, TrackingResult,
    BoundingBox, AlertLevel
)
from schemas.person_detection import PersonInfo, PersonDetectionResult
from core.config import get_settings

logger = logging.getLogger(__name__)
settings = get_settings()


class BehaviorState(str, Enum):
    """行为状态枚举"""
    NORMAL = "normal"
    SUSPICIOUS = "suspicious"
    DANGEROUS = "dangerous"
    EMERGENCY = "emergency"


@dataclass
class TrajectoryPoint:
    """轨迹点"""
    x: float
    y: float
    timestamp: datetime
    velocity: Optional[Tuple[float, float]] = None
    acceleration: Optional[Tuple[float, float]] = None


@dataclass
class PersonTrack:
    """人员轨迹"""
    track_id: str
    person_id: str
    trajectory: deque
    start_time: datetime
    last_update: datetime
    is_active: bool = True
    behavior_state: BehaviorState = BehaviorState.NORMAL
    attributes: Dict[str, Any] = None
    
    def __post_init__(self):
        if self.attributes is None:
            self.attributes = {}
        if not isinstance(self.trajectory, deque):
            self.trajectory = deque(maxlen=100)  # 保持最近100个点


class CrowdAnalyzer:
    """人群分析器"""
    
    def __init__(self, density_threshold: float = 0.3, crowd_threshold: int = 5):
        self.density_threshold = density_threshold
        self.crowd_threshold = crowd_threshold
    
    def analyze_crowd_density(self, persons: List[PersonInfo], image_size: Tuple[int, int]) -> Dict[str, Any]:
        """分析人群密度"""
        if not persons:
            return {
                "density": 0.0,
                "person_count": 0,
                "is_crowded": False,
                "hotspots": []
            }
        
        width, height = image_size
        total_area = width * height
        
        # 计算人员占用的总面积
        total_person_area = sum(
            (person.bbox.x2 - person.bbox.x1) * (person.bbox.y2 - person.bbox.y1)
            for person in persons
        )
        
        density = total_person_area / total_area
        is_crowded = density > self.density_threshold or len(persons) > self.crowd_threshold
        
        # 检测热点区域
        hotspots = self._detect_hotspots(persons, image_size)
        
        return {
            "density": density,
            "person_count": len(persons),
            "is_crowded": is_crowded,
            "hotspots": hotspots,
            "average_person_size": total_person_area / len(persons) if persons else 0
        }
    
    def _detect_hotspots(self, persons: List[PersonInfo], image_size: Tuple[int, int]) -> List[Dict[str, Any]]:
        """检测人群聚集热点"""
        if len(persons) < 3:
            return []
        
        width, height = image_size
        grid_size = 50  # 网格大小
        grid_width = width // grid_size
        grid_height = height // grid_size
        
        # 创建密度网格
        density_grid = np.zeros((grid_height, grid_width))
        
        for person in persons:
            center_x = (person.bbox.x1 + person.bbox.x2) / 2
            center_y = (person.bbox.y1 + person.bbox.y2) / 2
            
            grid_x = int(center_x // grid_size)
            grid_y = int(center_y // grid_size)
            
            if 0 <= grid_x < grid_width and 0 <= grid_y < grid_height:
                density_grid[grid_y, grid_x] += 1
        
        # 查找高密度区域
        hotspots = []
        threshold = max(2, len(persons) * 0.2)  # 动态阈值
        
        for y in range(grid_height):
            for x in range(grid_width):
                if density_grid[y, x] >= threshold:
                    hotspot = {
                        "x": x * grid_size,
                        "y": y * grid_size,
                        "width": grid_size,
                        "height": grid_size,
                        "person_count": int(density_grid[y, x]),
                        "density": density_grid[y, x] / (grid_size * grid_size)
                    }
                    hotspots.append(hotspot)
        
        return hotspots


class BehaviorAnalyzer:
    """行为分析器"""
    
    def __init__(self):
        self.speed_threshold_running = 50.0  # 像素/秒
        self.speed_threshold_fast = 30.0
        self.loitering_time_threshold = 30.0  # 秒
        self.direction_change_threshold = 45.0  # 度
        self.interaction_distance_threshold = 100.0  # 像素
    
    def analyze_behavior(self, track: PersonTrack) -> List[BehaviorType]:
        """分析单个轨迹的行为"""
        behaviors = []
        
        if len(track.trajectory) < 2:
            return [BehaviorType.NORMAL]
        
        # 计算速度和方向
        velocities = self._calculate_velocities(track.trajectory)
        directions = self._calculate_directions(track.trajectory)
        
        # 检测跑步行为
        if self._detect_running(velocities):
            behaviors.append(BehaviorType.RUNNING)
        
        # 检测徘徊行为
        if self._detect_loitering(track, directions):
            behaviors.append(BehaviorType.LOITERING)
        
        # 检测异常停留
        if self._detect_abnormal_stop(velocities):
            behaviors.append(BehaviorType.LOITERING)
        
        # 检测急剧方向变化
        if self._detect_erratic_movement(directions):
            behaviors.append(BehaviorType.RUNNING)  # 可能是逃跑或追逐
        
        return behaviors if behaviors else [BehaviorType.NORMAL]
    
    def analyze_group_behavior(self, tracks: List[PersonTrack]) -> List[BehaviorType]:
        """分析群体行为"""
        if len(tracks) < 2:
            return []
        
        behaviors = []
        
        # 检测人群聚集
        if self._detect_crowding(tracks):
            behaviors.append(BehaviorType.CROWDING)
        
        # 检测可能的冲突
        if self._detect_potential_conflict(tracks):
            behaviors.append(BehaviorType.FIGHTING)
        
        # 检测集体快速移动（可能是恐慌）
        if self._detect_panic_movement(tracks):
            behaviors.append(BehaviorType.RUNNING)
        
        return behaviors
    
    def _calculate_velocities(self, trajectory: deque) -> List[float]:
        """计算速度序列"""
        velocities = []
        points = list(trajectory)
        
        for i in range(1, len(points)):
            prev_point = points[i-1]
            curr_point = points[i]
            
            dx = curr_point.x - prev_point.x
            dy = curr_point.y - prev_point.y
            dt = (curr_point.timestamp - prev_point.timestamp).total_seconds()
            
            if dt > 0:
                speed = np.sqrt(dx*dx + dy*dy) / dt
                velocities.append(speed)
        
        return velocities
    
    def _calculate_directions(self, trajectory: deque) -> List[float]:
        """计算方向序列（角度）"""
        directions = []
        points = list(trajectory)
        
        for i in range(1, len(points)):
            prev_point = points[i-1]
            curr_point = points[i]
            
            dx = curr_point.x - prev_point.x
            dy = curr_point.y - prev_point.y
            
            angle = np.arctan2(dy, dx) * 180 / np.pi
            directions.append(angle)
        
        return directions
    
    def _detect_running(self, velocities: List[float]) -> bool:
        """检测跑步行为"""
        if not velocities:
            return False
        
        # 检查是否有连续的高速移动
        high_speed_count = sum(1 for v in velocities[-10:] if v > self.speed_threshold_running)
        return high_speed_count >= 3
    
    def _detect_loitering(self, track: PersonTrack, directions: List[float]) -> bool:
        """检测徘徊行为"""
        # 检查是否在同一区域停留过长时间
        duration = (track.last_update - track.start_time).total_seconds()
        
        if duration < self.loitering_time_threshold:
            return False
        
        # 检查移动范围是否很小
        points = list(track.trajectory)
        if len(points) < 10:
            return False
        
        xs = [p.x for p in points]
        ys = [p.y for p in points]
        
        x_range = max(xs) - min(xs)
        y_range = max(ys) - min(ys)
        
        # 如果移动范围很小但时间很长，认为是徘徊
        return x_range < 50 and y_range < 50
    
    def _detect_abnormal_stop(self, velocities: List[float]) -> bool:
        """检测异常停止"""
        if len(velocities) < 5:
            return False
        
        # 检查最近是否突然停止
        recent_velocities = velocities[-5:]
        return all(v < 5.0 for v in recent_velocities) and len(velocities) > 10
    
    def _detect_erratic_movement(self, directions: List[float]) -> bool:
        """检测不规律移动"""
        if len(directions) < 5:
            return False
        
        # 计算方向变化
        direction_changes = []
        for i in range(1, len(directions)):
            change = abs(directions[i] - directions[i-1])
            # 处理角度跨越180度的情况
            if change > 180:
                change = 360 - change
            direction_changes.append(change)
        
        # 检查是否有频繁的大幅度方向变化
        large_changes = sum(1 for change in direction_changes[-10:] if change > self.direction_change_threshold)
        return large_changes >= 3
    
    def _detect_crowding(self, tracks: List[PersonTrack]) -> bool:
        """检测人群聚集"""
        if len(tracks) < 5:
            return False
        
        # 获取最新位置
        current_positions = []
        for track in tracks:
            if track.trajectory:
                latest_point = track.trajectory[-1]
                current_positions.append((latest_point.x, latest_point.y))
        
        if len(current_positions) < 5:
            return False
        
        # 计算平均距离
        total_distance = 0
        count = 0
        
        for i in range(len(current_positions)):
            for j in range(i+1, len(current_positions)):
                x1, y1 = current_positions[i]
                x2, y2 = current_positions[j]
                distance = np.sqrt((x2-x1)**2 + (y2-y1)**2)
                total_distance += distance
                count += 1
        
        if count == 0:
            return False
        
        avg_distance = total_distance / count
        return avg_distance < self.interaction_distance_threshold
    
    def _detect_potential_conflict(self, tracks: List[PersonTrack]) -> bool:
        """检测潜在冲突"""
        # 简化的冲突检测：查找快速接近的轨迹
        for i in range(len(tracks)):
            for j in range(i+1, len(tracks)):
                track1, track2 = tracks[i], tracks[j]
                
                if not track1.trajectory or not track2.trajectory:
                    continue
                
                # 获取最近的位置
                pos1 = track1.trajectory[-1]
                pos2 = track2.trajectory[-1]
                
                distance = np.sqrt((pos2.x - pos1.x)**2 + (pos2.y - pos1.y)**2)
                
                # 如果距离很近且都在快速移动
                if distance < 80:  # 很近的距离
                    # 检查速度
                    if len(track1.trajectory) >= 2 and len(track2.trajectory) >= 2:
                        vel1 = self._calculate_velocities(track1.trajectory)
                        vel2 = self._calculate_velocities(track2.trajectory)
                        
                        if vel1 and vel2 and vel1[-1] > 20 and vel2[-1] > 20:
                            return True
        
        return False
    
    def _detect_panic_movement(self, tracks: List[PersonTrack]) -> bool:
        """检测恐慌性移动"""
        if len(tracks) < 3:
            return False
        
        fast_moving_count = 0
        
        for track in tracks:
            if len(track.trajectory) >= 2:
                velocities = self._calculate_velocities(track.trajectory)
                if velocities and velocities[-1] > self.speed_threshold_fast:
                    fast_moving_count += 1
        
        # 如果大部分人都在快速移动，可能是恐慌
        return fast_moving_count >= len(tracks) * 0.6


class BehaviorAnalysisService:
    """行为分析服务"""
    
    def __init__(self):
        self.tracks: Dict[str, PersonTrack] = {}
        self.crowd_analyzer = CrowdAnalyzer()
        self.behavior_analyzer = BehaviorAnalyzer()
        self.analysis_results: List[BehaviorAnalysisResult] = []
        self.max_track_age = 300  # 5分钟
        self.analysis_interval = 1.0  # 1秒分析一次
        
        # 启动后台分析任务
        self._analysis_task = None
        self._running = False
    
    async def start_analysis(self):
        """启动行为分析"""
        if self._running:
            return
        
        self._running = True
        self._analysis_task = asyncio.create_task(self._analysis_loop())
        logger.info("Behavior analysis service started")
    
    async def stop_analysis(self):
        """停止行为分析"""
        self._running = False
        if self._analysis_task:
            self._analysis_task.cancel()
            try:
                await self._analysis_task
            except asyncio.CancelledError:
                pass
        logger.info("Behavior analysis service stopped")
    
    async def _analysis_loop(self):
        """分析循环"""
        while self._running:
            try:
                await self._perform_analysis()
                await asyncio.sleep(self.analysis_interval)
            except asyncio.CancelledError:
                break
            except Exception as e:
                logger.error(f"Error in analysis loop: {e}")
                await asyncio.sleep(1.0)
    
    async def _perform_analysis(self):
        """执行分析"""
        current_time = datetime.now()
        
        # 清理过期轨迹
        self._cleanup_old_tracks(current_time)
        
        if not self.tracks:
            return
        
        # 分析个体行为
        individual_behaviors = {}
        for track_id, track in self.tracks.items():
            behaviors = self.behavior_analyzer.analyze_behavior(track)
            individual_behaviors[track_id] = behaviors
        
        # 分析群体行为
        active_tracks = [track for track in self.tracks.values() if track.is_active]
        group_behaviors = self.behavior_analyzer.analyze_group_behavior(active_tracks)
        
        # 生成分析结果
        await self._generate_analysis_results(individual_behaviors, group_behaviors, current_time)
    
    def _cleanup_old_tracks(self, current_time: datetime):
        """清理过期轨迹"""
        expired_tracks = []
        
        for track_id, track in self.tracks.items():
            age = (current_time - track.last_update).total_seconds()
            if age > self.max_track_age:
                expired_tracks.append(track_id)
            elif age > 30:  # 30秒未更新标记为非活跃
                track.is_active = False
        
        for track_id in expired_tracks:
            del self.tracks[track_id]
    
    async def _generate_analysis_results(
        self, 
        individual_behaviors: Dict[str, List[BehaviorType]], 
        group_behaviors: List[BehaviorType],
        timestamp: datetime
    ):
        """生成分析结果"""
        # 处理个体行为结果
        for track_id, behaviors in individual_behaviors.items():
            track = self.tracks[track_id]
            
            for behavior in behaviors:
                if behavior != BehaviorType.NORMAL:
                    result = BehaviorAnalysisResult(
                        analysis_id=str(uuid4()),
                        camera_id="unknown",  # 需要从上下文获取
                        behavior_type=behavior,
                        confidence=0.8,  # 简化的置信度
                        description=self._get_behavior_description(behavior),
                        involved_tracks=[track_id],
                        location=self._get_track_location(track),
                        duration=self._get_track_duration(track),
                        timestamp=timestamp,
                        metadata={
                            "track_id": track_id,
                            "person_id": track.person_id,
                            "behavior_state": track.behavior_state.value
                        }
                    )
                    
                    self.analysis_results.append(result)
        
        # 处理群体行为结果
        for behavior in group_behaviors:
            result = BehaviorAnalysisResult(
                analysis_id=str(uuid4()),
                camera_id="unknown",
                behavior_type=behavior,
                confidence=0.7,
                description=self._get_behavior_description(behavior),
                involved_tracks=list(self.tracks.keys()),
                location=None,  # 群体行为可能没有特定位置
                duration=None,
                timestamp=timestamp,
                metadata={
                    "track_count": len(self.tracks),
                    "analysis_type": "group_behavior"
                }
            )
            
            self.analysis_results.append(result)
        
        # 保持最近1000条结果
        if len(self.analysis_results) > 1000:
            self.analysis_results = self.analysis_results[-1000:]
    
    def _get_behavior_description(self, behavior: BehaviorType) -> str:
        """获取行为描述"""
        descriptions = {
            BehaviorType.NORMAL: "正常行为",
            BehaviorType.RUNNING: "检测到快速移动或跑步行为",
            BehaviorType.FIGHTING: "检测到潜在冲突或打斗行为",
            BehaviorType.FALLING: "检测到跌倒行为",
            BehaviorType.LOITERING: "检测到徘徊或异常停留行为",
            BehaviorType.CROWDING: "检测到人群聚集",
            BehaviorType.INTRUSION: "检测到入侵行为",
            BehaviorType.ABANDONED_OBJECT: "检测到遗留物品"
        }
        return descriptions.get(behavior, "未知行为")
    
    def _get_track_location(self, track: PersonTrack) -> Optional[BoundingBox]:
        """获取轨迹位置"""
        if not track.trajectory:
            return None
        
        latest_point = track.trajectory[-1]
        # 简化的边界框，实际应该基于检测结果
        return BoundingBox(
            x=max(0, latest_point.x - 25),
            y=max(0, latest_point.y - 50),
            width=50,
            height=100
        )
    
    def _get_track_duration(self, track: PersonTrack) -> float:
        """获取轨迹持续时间"""
        return (track.last_update - track.start_time).total_seconds()
    
    async def update_tracks(self, detection_result: PersonDetectionResult):
        """更新轨迹信息"""
        current_time = datetime.now()
        
        for person_data in detection_result.persons:
            person_id = person_data.get("person_id")
            tracking_id = person_data.get("tracking_id")
            center = person_data.get("center", [0, 0])
            
            if not tracking_id:
                continue
            
            # 创建轨迹点
            trajectory_point = TrajectoryPoint(
                x=center[0],
                y=center[1],
                timestamp=current_time
            )
            
            if tracking_id in self.tracks:
                # 更新现有轨迹
                track = self.tracks[tracking_id]
                track.trajectory.append(trajectory_point)
                track.last_update = current_time
                track.is_active = True
                
                # 计算速度和加速度
                if len(track.trajectory) >= 2:
                    self._calculate_motion_attributes(track)
            else:
                # 创建新轨迹
                track = PersonTrack(
                    track_id=tracking_id,
                    person_id=person_id,
                    trajectory=deque([trajectory_point], maxlen=100),
                    start_time=current_time,
                    last_update=current_time,
                    is_active=True
                )
                
                self.tracks[tracking_id] = track
    
    def _calculate_motion_attributes(self, track: PersonTrack):
        """计算运动属性"""
        if len(track.trajectory) < 2:
            return
        
        points = list(track.trajectory)
        current_point = points[-1]
        previous_point = points[-2]
        
        # 计算速度
        dx = current_point.x - previous_point.x
        dy = current_point.y - previous_point.y
        dt = (current_point.timestamp - previous_point.timestamp).total_seconds()
        
        if dt > 0:
            vx = dx / dt
            vy = dy / dt
            current_point.velocity = (vx, vy)
            
            # 计算加速度
            if len(points) >= 3 and previous_point.velocity:
                prev_vx, prev_vy = previous_point.velocity
                ax = (vx - prev_vx) / dt
                ay = (vy - prev_vy) / dt
                current_point.acceleration = (ax, ay)
    
    async def analyze_crowd_density(
        self, 
        detection_result: PersonDetectionResult,
        image_size: Tuple[int, int]
    ) -> Dict[str, Any]:
        """分析人群密度"""
        # 转换检测结果为PersonInfo格式
        persons = []
        for person_data in detection_result.persons:
            bbox_data = person_data.get("bbox", [0, 0, 100, 100])
            
            # 创建简化的PersonInfo对象
            person = type('PersonInfo', (), {
                'bbox': type('BBox', (), {
                    'x1': bbox_data[0],
                    'y1': bbox_data[1], 
                    'x2': bbox_data[2],
                    'y2': bbox_data[3]
                })()
            })()
            
            persons.append(person)
        
        return self.crowd_analyzer.analyze_crowd_density(persons, image_size)
    
    async def get_analysis_results(
        self, 
        camera_id: Optional[str] = None,
        behavior_types: Optional[List[BehaviorType]] = None,
        start_time: Optional[datetime] = None,
        end_time: Optional[datetime] = None,
        limit: int = 100
    ) -> List[BehaviorAnalysisResult]:
        """获取分析结果"""
        results = self.analysis_results
        
        # 过滤条件
        if camera_id:
            results = [r for r in results if r.camera_id == camera_id]
        
        if behavior_types:
            results = [r for r in results if r.behavior_type in behavior_types]
        
        if start_time:
            results = [r for r in results if r.timestamp >= start_time]
        
        if end_time:
            results = [r for r in results if r.timestamp <= end_time]
        
        # 按时间倒序排列并限制数量
        results.sort(key=lambda x: x.timestamp, reverse=True)
        return results[:limit]
    
    async def get_active_tracks(self, camera_id: Optional[str] = None) -> List[Dict[str, Any]]:
        """获取活跃轨迹"""
        active_tracks = []
        
        for track in self.tracks.values():
            if not track.is_active:
                continue
            
            track_info = {
                "track_id": track.track_id,
                "person_id": track.person_id,
                "start_time": track.start_time.isoformat(),
                "last_update": track.last_update.isoformat(),
                "behavior_state": track.behavior_state.value,
                "trajectory_length": len(track.trajectory),
                "attributes": track.attributes
            }
            
            # 添加最新位置
            if track.trajectory:
                latest_point = track.trajectory[-1]
                track_info["current_position"] = {
                    "x": latest_point.x,
                    "y": latest_point.y,
                    "timestamp": latest_point.timestamp.isoformat()
                }
                
                if latest_point.velocity:
                    track_info["velocity"] = {
                        "vx": latest_point.velocity[0],
                        "vy": latest_point.velocity[1],
                        "speed": np.sqrt(latest_point.velocity[0]**2 + latest_point.velocity[1]**2)
                    }
            
            active_tracks.append(track_info)
        
        return active_tracks
    
    async def process_video_frame(self, frame: np.ndarray, metadata: Dict[str, Any] = None) -> Dict[str, Any]:
        """处理视频帧进行行为分析"""
        try:
            camera_id = metadata.get('camera_id', 'unknown') if metadata else 'unknown'
            frame_timestamp = datetime.fromisoformat(metadata.get('frame_timestamp')) if metadata and metadata.get('frame_timestamp') else datetime.now()
            
            # 模拟人员检测结果（实际应该从人员检测服务获取）
            mock_detection_result = self._create_mock_detection_result(frame, camera_id, frame_timestamp)
            
            # 更新轨迹
            await self.update_tracks(mock_detection_result)
            
            # 分析人群密度
            image_size = (frame.shape[1], frame.shape[0])
            crowd_analysis = await self.analyze_crowd_density(mock_detection_result, image_size)
            
            # 获取最近的分析结果
            recent_results = [
                r for r in self.analysis_results 
                if r.timestamp > datetime.now() - timedelta(minutes=1)
            ]
            
            return {
                "algorithm": "behavior_analysis",
                "camera_id": camera_id,
                "frame_timestamp": frame_timestamp.isoformat(),
                "processing_timestamp": datetime.now().isoformat(),
                "results": {
                    "active_tracks": len([t for t in self.tracks.values() if t.is_active]),
                    "crowd_analysis": crowd_analysis,
                    "recent_behaviors": [
                        {
                            "behavior_type": r.behavior_type.value,
                            "confidence": r.confidence,
                            "description": r.description,
                            "involved_tracks": r.involved_tracks
                        } for r in recent_results[-5:]  # 最近5个行为事件
                    ],
                    "track_summary": [
                        {
                            "track_id": track.track_id,
                            "person_id": track.person_id,
                            "behavior_state": track.behavior_state.value,
                            "trajectory_length": len(track.trajectory)
                        } for track in list(self.tracks.values())[:10]  # 最多10个轨迹
                    ]
                },
                "confidence": 0.85,
                "processing_time": 0.1
            }
            
        except Exception as e:
            logger.error(f"行为分析处理视频帧失败: {e}")
            return {
                "algorithm": "behavior_analysis",
                "camera_id": metadata.get('camera_id', 'unknown') if metadata else 'unknown',
                "error": str(e),
                "processing_timestamp": datetime.now().isoformat()
            }
    
    def _create_mock_detection_result(self, frame: np.ndarray, camera_id: str, timestamp: datetime):
        """创建模拟检测结果"""
        height, width = frame.shape[:2]
        
        # 生成随机数量的人员
        num_persons = np.random.randint(0, 8)
        persons = []
        
        for i in range(num_persons):
            # 随机生成边界框
            x1 = np.random.randint(0, width - 100)
            y1 = np.random.randint(0, height - 150)
            x2 = x1 + np.random.randint(50, 100)
            y2 = y1 + np.random.randint(100, 150)
            
            # 确保边界框在图像范围内
            x2 = min(x2, width)
            y2 = min(y2, height)
            
            person_data = {
                "person_id": f"person_{i}",
                "tracking_id": f"track_{camera_id}_{i}",
                "bbox": [x1, y1, x2, y2],
                "center": [(x1 + x2) / 2, (y1 + y2) / 2],
                "confidence": np.random.uniform(0.7, 0.95)
            }
            persons.append(person_data)
        
        # 创建检测结果对象
        return type('PersonDetectionResult', (), {
            'camera_id': camera_id,
            'timestamp': timestamp,
            'persons': persons,
            'total_count': len(persons)
        })()

    async def get_behavior_statistics(
        self, 
        time_range: timedelta = timedelta(hours=1)
    ) -> Dict[str, Any]:
        """获取行为统计"""
        end_time = datetime.now()
        start_time = end_time - time_range
        
        # 获取时间范围内的结果
        results = [
            r for r in self.analysis_results 
            if start_time <= r.timestamp <= end_time
        ]
        
        # 统计各种行为
        behavior_counts = defaultdict(int)
        for result in results:
            behavior_counts[result.behavior_type.value] += 1
        
        # 计算平均置信度
        avg_confidence = sum(r.confidence for r in results) / len(results) if results else 0
        
        # 统计涉及的轨迹数
        involved_tracks = set()
        for result in results:
            involved_tracks.update(result.involved_tracks)
        
        return {
            "time_range": {
                "start": start_time.isoformat(),
                "end": end_time.isoformat()
            },
            "total_events": len(results),
            "behavior_counts": dict(behavior_counts),
            "average_confidence": avg_confidence,
            "unique_tracks_involved": len(involved_tracks),
            "active_tracks": len([t for t in self.tracks.values() if t.is_active])
        }


# 全局行为分析服务实例
behavior_analysis_service = BehaviorAnalysisService()